const socket = io("http://localhost:3000");
const roomBox = document.getElementById("room_box");
const messagesBox = document.getElementById("message_box");
const messageForm = document.getElementById("send_box");
const messageInput = document.getElementById("message_input");

if (messageForm !== null) {
  const useName = prompt("您的姓名是：");
  appendMessage("你已经加入聊天系统");
  socket.emit("new-user", roomName, useName); // 发送姓名到执行的socketio接收器中

  // 为表单绑定事件，并发送相应消息给socketio服务
  messageForm.addEventListener("submit", (e) => {
    e.preventDefault();
    const message = messageInput.value;
    appendMessage(`您发了：${message}`);
    socket.emit("send-chat-message", roomName, message); // 向socket.io服务器发送消息
    messageInput.value = "";
  });
}

// 开启chat-message类消息监听
socket.on("chat-message", (data) => {
  appendMessage(`用户${data.name}说了: ${data.message}`);
});

// 开启user-connected类消息监听
socket.on("user-connected", (data) => {
  appendMessage(`${data} 已连接`);
});

// 开启user-disconnected类消息监听
socket.on("user-disconnected", (data) => {
  appendMessage(`${data} 已下线`);
});

socket.on("room-create", (room) => {
  const _divEL = document.createElement("div");
  _divEL.innerText = room;

  const _aEl = document.createElement("a");
  _aEl.innerText = `您已加入房间`;
  _aEl.href = `/${room}`;

  roomBox.append(_divEL);
  roomBox.append(_aEl);
});

// 显示消息
function appendMessage(message) {
  if (messagesBox) {
    const messageEl = document.createElement("div");
    messageEl.innerText = message;
    messagesBox.append(messageEl);
  }
}
